<template>
  <el-form :model="dataForm" :rules="rules" class="form-box" label-position="top" ref="dataFormRef"
    @keyup.enter="dataFormSubmitHandle()" label-width="120px">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="idCard" label="身份证号">
          <el-input v-model="dataForm.idCard" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="stuNum" label="学号">
          <el-input v-model="dataForm.stuNum" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="gradeId" label="年级">
          <el-select v-model="dataForm.gradeId" clearable placeholder="请选择" @change="gradeChange">
            <el-option :value="item.id" :label="item.text" v-for="(item, index) in gradeList" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="classId" label="班级">
          <el-select v-model="dataForm.classId" clearable placeholder="请选择">
            <el-option :value="item.id" :label="item.text" v-for="(item, index) in classList" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item class="footer-btn">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { useAppStore } from "@/store";

const store = useAppStore();
const route = useRoute();
const router = useRouter();
const row: any = JSON.parse(route.query?.row as string || '{}');
const dataFormRef = ref();
const gradeList = ref<any[]>([]);
const classList = ref<any[]>([]);

const dataForm = reactive({
  id: "",
  name: "",
  idCard: "",
  stuNum: "",
  gradeId: "",
  gradeName: "",
  classId: "",
  className: "",
});

const validateIdCard = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('必填项不能为空'))
  } else {
    var reg = /^(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!reg.test(value)) {
      callback(new Error('身份证格式错误'));
    }
    callback()
  }
}

const rules = ref({
  name: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  idCard: [{ required: true, validator: validateIdCard, trigger: "blur" }],
  gradeId: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  classId: [{ required: true, message: "必填项不能为空", trigger: "change" }],
});

const init = () => {
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getGradeList()]).then(() => {
    if (row?.id) {
      Object.assign(dataForm, row);
      getClassList(row.gradeId);
    }
  });
};

// 获取年级
const getGradeList = () => {
  return baseService.get("/study/grade/select", { deptId: store.state.user.deptId }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    gradeList.value = res.data;
  });
};

// 获取班级
const getClassList = (gradeId: string) => {
  return baseService.get("/study/class/select", { gradeId }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    classList.value = res.data;
  });
};

const gradeChange = (e: string) => {
  dataForm.classId = "";
  getClassList(e);
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/study/student", {
      ...dataForm,
    }).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          router.push('/study/student');
        }
      });
    });
  });
};

const cancelHandle = () => {
  router.go(-1);
};

onMounted(() => {
  init();
})
</script>
